//
//  HttpClient.m
//  OAProject
//
//  Created by yhj on 2017/2/21.
//  Copyright © 2017年 cdnunion. All rights reserved.
//

#import "HttpClient.h"

@implementation HttpClient

+(HttpClient *)shareClient
{
    NSURL *baseURL=[NSURL URLWithString:kBaseUrl];
    static HttpClient *httpClient=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpClient=[[HttpClient alloc]initWithBaseURL:baseURL];
    });
    return httpClient;
}

-(id)initWithBaseURL:(NSURL *)url
{
    NSParameterAssert(url);

    self=[super initWithBaseURL:url];
    if (self) {
        NSOperationQueue *operationQueue=self.operationQueue;
        __weak typeof(self) weakSelf=self;
        [weakSelf.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            weakSelf.reachabilityStatus=status;
            switch (status) {
                case AFNetworkReachabilityStatusReachableViaWWAN:
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    [operationQueue setSuspended:NO];
                    break;

                case AFNetworkReachabilityStatusNotReachable:
                default:
                    [operationQueue setSuspended:YES];
                    break;
            }
        }];
        [weakSelf.reachabilityManager startMonitoring];
    }
    return self;
}

/**
 *  发起网络请求
 *
 *  @param path       请求接口URI
 *  @param method     请求类型(GET/POST)
 *  @param parameters API参数字典
 *  @param success    成功block
 *  @param failure    失败block
 */
- (void)requestPath:(NSString *)path
             method:(NSString *)method
         parameters:(NSDictionary *)parameters
            success:(void (^)(NSURLSessionTask *operation, id responseObject))success
            failure:(void (^)(NSURLSessionTask *operation, NSError *error))failure
{

#ifndef TARGET_OS_IOS

    // 显示联网状态
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

#endif
    // 2.设置非校验证书模式
    super.securityPolicy=[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    // 是否允许无效证书（也就是自建的证书），默认为NO
    super.securityPolicy.allowInvalidCertificates=YES;
    [super.securityPolicy setValidatesDomainName:YES];

    [super requestPath:path method:method parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {

        [self successResultWithOperation:operation responseObject:responseObject];

        if (success)
        {
            success(operation,responseObject);
        }

    } failure:^(NSURLSessionDataTask *operation, NSError *error) {

        NSLog(@"sdsdhgds666652353---%@",error);

        [self failureResultWithOperation:operation responseObject:error];

        if (failure)
        {
            failure(operation,error);
        }
    }];
}


// 成功回调
-(void)successResultWithOperation:(NSURLSessionTask *)operation responseObject:(id)responseObject
{
    NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)operation.response;
    NSInteger stateCode=[httpResponse statusCode];
    NSLog(@"success stateCode---%ld",(long)stateCode);
}

// 失败回调
-(NSString *)failureResultWithOperation:(NSURLSessionTask *)operation responseObject:(NSError *)error
{

    NSData *errorData=[[error userInfo] objectForKey:@"com.alamofire.serialization.response.error.data"];
    id jsonObject=[NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
    NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)operation.response;
    NSInteger stateCode=[httpResponse statusCode];
    if (stateCode==0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GKNetworkReachabilityStatusNotReachable" object:nil];
    }
    
     if (stateCode==403)
    {

    }
    return [jsonObject valueForKey:@"error"];
}

/**
 *  发起网络请求(带二进制数据)
 *
 *  @param path             请求接口URI
 *  @param method           请求类型(GET/POST)
 *  @param parameters       API参数字典
 *  @param dataParameters    Data参数字典
 *  @param success           成功block
 *  @param failure           失败block
 */
- (void)requestPath:(NSString *)path
//             method:(NSString *)method
         parameters:(NSDictionary *)parameters
     dataParameters:(NSDictionary *)dataParameters
            success:(void (^)(NSURLSessionDataTask *operation, id responseObject))success
            failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure
{

#ifndef TARGET_OS_IOS

    // 显示联网状态
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

#endif

    [super requestPath:path parameters:parameters dataParameters:dataParameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [self successResultWithOperation:operation responseObject:responseObject];

                if (success)
                {
                    success(operation, responseObject);
                }
       }
        failure: ^(NSURLSessionDataTask *operation, NSError *error){
               [self failureResultWithOperation:operation responseObject:error];
               if (failure) {
                   failure(operation, error);
               }
        }];
}


/**
 *  取消所有网络请求
 */
+ (void)cancelAllHTTPOperations
{
    [[HttpClient shareClient].operationQueue cancelAllOperations];
}

@end
